var m_PlanID =null; // 计划单主键

//初始化
$(function () {

    $('#A').window('close');  // close a window
    $("#billcode").textbox({disabled: true});
    $("#billcodetype").combobox({disabled: true});

    //获取所有下拉的data
    getdropdownDataA();
    setsizeA();
    addplanA();

});


//保存  OK
function saveA() {
    var etime = new Date();
    var m_date = format(etime);
    var m_billdate= $('#billcodeDate').datebox('getValue') + ' ' +getnewdatetime(etime);
    console.log(m_date);
    console.log(m_date.substring(m_date.length-8,m_date.length));
    console.log(m_date.substring(0,10));

    var m_billcode = $("#billcode").textbox('getValue');
    var m_billcodetype = $("#billcodetype").combobox('getText');

    var m_ddh = $("#ddh").textbox('getValue');
    var m_supplier = $("#supplier").combobox('getText');
    var m_khname = $("#clientName").combobox('getText');
    var m_khid = $("#clientName").combobox('getValue');
    var m_pm = $("#pm").combobox('getText');

    var m_ps = $("#ps").textbox('getValue');
    var m_planqty = $("#planqty").textbox('getValue');
    var m_cang = $("#cw").textbox('getValue');
    var m_memo = $("#memo").textbox('getValue');

    // isNaN(num) 返回true代表非数字,返回false,代表是有效数字
    if (isNaN(m_ps)===true){$.messager.alert('提示','请输入正确的件数！');return;}
    if (isNaN(m_planqty)===true){$.messager.alert('提示','请输入正确的公斤数！');return;}
    if (m_pm.length <= 0) {$.messager.alert('提示','品名为空，不允许保存！');return;}
    if (m_khname.length <= 0) {$.messager.alert('提示','客户为空，不允许保存！');return;}
    if (m_planqty.length <= 0) {$.messager.alert('提示','计划重量为空，不允许保存！');return;}

    //主键为空时新增
    if (m_PlanID==null) {
        var SQLstr={
            "bill_date":m_billdate,
            "bill_type": m_billcodetype,
            "bill_number": m_ddh,
            "supplier_sid": m_supplier,
            "client_sid": m_khid,
            "goods_sid": m_pm,
            "amount": m_ps,
            "kilo": m_planqty,
            "position": m_cang,
            "remark": m_memo,
            // "bill_code": "string", //单据编号 暂无
            // "operator_name": "string",
            // "operator_sid": "string",
        };

        console.log(SQLstr);
        $.ajax({
            url: strLin + 'material/insertSelective',
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify(SQLstr),
            contentType: "application/json;charset=UTF-8",
            success: function (data) {
                console.log('保存成功data');
                console.log(data);
                m_PlanID=data.data.iid;
                console.log("m_PlanID= " + m_PlanID)
                $("#billcode").textbox('setValue',data.data.bill_code);
                $.messager.alert('提示','保存成功！')
                // getplanIDA();
                closeButtonA();
                setStatusA(1);
                refresh()
            }
        });
    }else {
        //修改
        var str ={
            "iid":m_PlanID,
            "bill_date":m_billdate,
            "bill_type": m_billcodetype,
            "bill_number": m_ddh,
            "supplier_sid": m_supplier,
            "client_sid": m_khid,
            "goods_sid": m_pm,
            "amount": m_ps,
            "kilo": m_planqty,
            "position": m_cang,
            "remark": m_memo,
             "bill_code": m_billcode, //单据编号 暂无
            // "operator_name": "string",
            // "operator_sid": "string",
        };

        console.log(str);
        $.ajax({
            url: strLin + 'material/updateByPrimaryKeySelective',
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify(str),
            contentType: "application/json;charset=UTF-8",
            success: function (data) {
                console.log('修改成功data');
                $.messager.alert('提示','修改保存成功！');
                closeButtonA();
                setStatusA(1);
                refresh()
            }
        });
    }
}


//修改计划单 恢复按钮和文本框为可用  OK
function updateplanA() {
    if (m_PlanID ==null) {
        return;
    }
    openButtonA();
    setStatusA(2);

}

//新增计划单  把所有文本清空  OK
function addplanA() {
    m_PlanID = null;
    console.log(getDay(0));

    $("#billcodeDate").datebox("setValue", getDay(0));

    //清空文本数据为空
    $("#billcode").textbox('setValue','');
    $("#ddh").textbox('setValue','');

    $("#supplier").combobox('setValue', '');
    $("#supplier").combobox('setText', '');
    $("#pm").combobox('setValue', '');
    $("#pm").combobox('setText', '');
    $("#clientName").combobox('setValue', '');
    $("#clientName").combobox('setText', '');

    $("#cw").textbox('setValue', '');
    $("#ps").textbox('setValue', '');
    $("#planqty").textbox('setValue', '');
    $("#memo").textbox('setValue', '');

    openButtonA();
    setStatusA(0);
}

//复制计划单  OK
function copyplanA() {
    if (m_PlanID == null) {
        $.messager.alert('提示','请打开有效单据，在进行复制！');
        return;
    }
    m_PlanID = null;

    openButtonA();
    setStatusA(2);
}

//删除当前单据  OK
function deleteplanA() {
    $.messager.defaults = {ok: "确定", cancel: "取消", width: 300, closable: false};
    $.messager.confirm('确认', '作废不可恢复,您确认要作废当前单据吗？', function (r) {
        if (r) {

            $('#D').window('open');

            // $.ajax({
            //     url: strLin + 'material/deleteByPrimaryKey/'+ m_PlanID,
            //     type: 'get',
            //     dataType: 'json',
            //     success: function (data) {
            //         console.log(data);
            //         $.messager.alert('提示','删除完成！')
            //         // movedownplanA();
            //         addplanA();
            //         refresh()
            //     }
            // });

        }
    });


}

function closeTabA() {
    addplanA();
    btn_refresh();
    $('#A').window('close');  // close a window
    setStatus(tabNumber);
}

//打开计划单
function openplanA(id) {
    m_PlanID = id;
    console.log(strLin + 'material/selectByPrimaryKey/'+ m_PlanID);
    $.ajax({
        url: strLin + 'material/selectByPrimaryKey/'+ m_PlanID,
        type: 'get',
        dataType: 'json',
        success: function (cdata) {
            let data=cdata.data;
            if (data) {
                m_PlanID = data.iid;

                $("#billcodeDate").datebox("setValue", data.bill_date);

                $("#billcode").textbox('setValue', data.bill_code);
                $("#ddh").textbox('setValue', data.bill_number);

                $("#billcodetype").combobox('setText', data.bill_type);
                $("#pm").combobox('setValue', data.goods_sid);
                $("#pm").combobox('setText', data.goods_sid);
                $("#clientName").combobox('setValue', data.client_sid);
                // $("#clientName").combobox('setText', data.client_name);
                $("#supplier").combobox('setValue', data.supplier_sid);

                $("#ps").textbox('setValue', data.amount);
                $("#planqty").textbox('setValue', data.kilo);
                $("#cw").textbox('setValue', data.position);
                $("#memo").textbox('setValue', data.remark);

                closeButtonA();
            }
        }
    })
}

/************************************************/

//保存之后设置保存按钮为灰色不可用
function closeButtonA() {
    $('#saveplanA').linkbutton('disable');
    //$('#saveplan').linkbutton('enable'); 取消灰色恢复可用

    $("#ddh").textbox({disabled: true});
    $("#supplier").combobox("disable");
    $("#clientName").combobox("disable");
    $("#pm").combobox("disable");
    $("#cw").textbox({disabled: true});

    $("#ps").textbox({disabled: true});
    $("#planqty").textbox({disabled: true});
    $("#memo").textbox({disabled: true});

    setsizeA();
}


//打开所有按钮和文本可用
function openButtonA() {
    $('#saveplanA').linkbutton('enable');  //取消灰色恢复可用

    $("#ddh").textbox({disabled: false});
    $("#supplier").combobox("enable");
    $("#clientName").combobox("enable");
    $("#pm").combobox("enable");

    $("#cw").textbox({disabled: false});
    $("#ps").textbox({disabled: false});
    $("#planqty").textbox({disabled: false});
    $("#memo").textbox({disabled: false});

    setsizeA();
}

/***************************************************/
//刷新下拉选择中的数据
function reloadA() {
    $.ajax({
        url: strLin + 'dynamicQuery/querySqlString/select sid,sname,Fun_GetPY(sname)code from contact',
        type: 'get',
        dataType: 'json',
        success: function (cdata) {
            $('#clientName').combobox({
                valueField: 'sid',
                textField: 'sname',
                data: cdata.data,
                panelWidth: 250,
                panelHeight: 300,
                missingMessage: '必输项,必须选择下拉菜单中的值,否则无法保存',
                // invalidMessage:'必输项,必须选择下拉菜单中的值,否则无法保存',
                idField: 'code',
                formatter: row => {
                    return row['sname'] + '-' + row['code'];
                },
                onSelect: row => {

                },
                filter: function (q, row) {
                    let options = $(this).combobox('options');
                    let textField = row[options.textField] || '';
                    let sIdField = row[options.valueField] || '';
                    let codeField = row[options.idField] || '';
                    // console.log(options);
                    return textField.toString().toUpperCase().indexOf(q.toUpperCase()) >= 0
                        || sIdField.toString().toUpperCase().indexOf(q.toUpperCase()) >= 0
                        || codeField.toString().toUpperCase().indexOf(q.toUpperCase()) >= 0;
                },
                onLoadSuccess: function () {
                    $(this).combobox('options').limitToList = true
                }
            });
            clientall = cdata.data
        }
    });
    //设置供应商下拉
    $.ajax({
        url: strLin + 'dynamicQuery/querySqlString/select sid,sname,Fun_GetPY(sid)code from supplier',
        type: 'get',
        dataType: 'json',
        success: function (cdata) {
            $('#supplier').combobox({
                valueField: 'sid',
                textField: 'sid',
                data: cdata.data,
                panelWidth: 250,
                panelHeight: 300,
                missingMessage: '必输项,必须选择下拉菜单中的值,否则无法保存',
                // invalidMessage:'必输项,必须选择下拉菜单中的值,否则无法保存',
                idField: 'code',
                formatter: row => {
                    return row['sid'] + '-' + row['code'];
                },
                onSelect: row => {

                },
                filter: function (q, row) {
                    let options = $(this).combobox('options');
                    let textField = row[options.textField] || '';
                    let sIdField = row[options.valueField] || '';
                    let codeField = row[options.idField] || '';
                    // console.log(options);
                    return textField.toString().toUpperCase().indexOf(q.toUpperCase()) >= 0
                        || sIdField.toString().toUpperCase().indexOf(q.toUpperCase()) >= 0
                        || codeField.toString().toUpperCase().indexOf(q.toUpperCase()) >= 0;
                },
                onLoadSuccess: function () {
                    $(this).combobox('options').limitToList = true
                }
            });
            clientall = cdata.data
        }
    });
    //设置品名下拉
    $.ajax({
        url: strLin + 'product/selectAll',
        type: 'get',
        dataType: 'json',
        success: function (cdata) {
            $('#pm').combobox({
                valueField: 'sid',
                textField: 'sid',
                data:cdata.data
            });
        }
    });
}

//设置所有下拉数据
function getdropdownDataA() {
    //设置客户下拉
    $.ajax({
        url: strLin + 'dynamicQuery/querySqlString/select sid,sname,Fun_GetPY(sname)code from contact',
        type: 'get',
        dataType: 'json',
        success: function (cdata) {
            $('#clientName').combobox({
                valueField: 'sid',
                textField: 'sname',
                data: cdata.data,
                panelWidth: 250,
                panelHeight: 300,
                missingMessage: '必输项,必须选择下拉菜单中的值,否则无法保存',
                // invalidMessage:'必输项,必须选择下拉菜单中的值,否则无法保存',
                idField: 'code',
                formatter: row => {
                    return row['sname'] + '-' + row['code'];
                },
                onSelect: row => {

                },
                filter: function (q, row) {
                    let options = $(this).combobox('options');
                    let textField = row[options.textField] || '';
                    let sIdField = row[options.valueField] || '';
                    let codeField = row[options.idField] || '';
                    // console.log(options);
                    return textField.toString().toUpperCase().indexOf(q.toUpperCase()) >= 0
                        || sIdField.toString().toUpperCase().indexOf(q.toUpperCase()) >= 0
                        || codeField.toString().toUpperCase().indexOf(q.toUpperCase()) >= 0;
                },
                onLoadSuccess: function () {
                    $(this).combobox('options').limitToList = true
                }
            });
            clientall = cdata.data
        }
    });
    //设置供应商下拉
    $.ajax({
        url: strLin + 'dynamicQuery/querySqlString/select sid,sname,Fun_GetPY(sid)code from supplier',
        type: 'get',
        dataType: 'json',
        success: function (cdata) {
            $('#supplier').combobox({
                valueField: 'sid',
                textField: 'sid',
                data: cdata.data,
                panelWidth: 250,
                panelHeight: 300,
                missingMessage: '必输项,必须选择下拉菜单中的值,否则无法保存',
                // invalidMessage:'必输项,必须选择下拉菜单中的值,否则无法保存',
                idField: 'code',
                formatter: row => {
                    return row['sid'] + '-' + row['code'];
                },
                onSelect: row => {

                },
                filter: function (q, row) {
                    let options = $(this).combobox('options');
                    let textField = row[options.textField] || '';
                    let sIdField = row[options.valueField] || '';
                    let codeField = row[options.idField] || '';
                    // console.log(options);
                    return textField.toString().toUpperCase().indexOf(q.toUpperCase()) >= 0
                        || sIdField.toString().toUpperCase().indexOf(q.toUpperCase()) >= 0
                        || codeField.toString().toUpperCase().indexOf(q.toUpperCase()) >= 0;
                },
                onLoadSuccess: function () {
                    $(this).combobox('options').limitToList = true
                }
            });
            clientall = cdata.data
        }
    });
    //设置品名下拉
    $.ajax({
        url: strLin + 'product/selectAll',
        type: 'get',
        dataType: 'json',
        success: function (cdata) {
            $('#pm').combobox({
                valueField: 'sid',
                textField: 'sid',
                data:cdata.data
            });
        }
    });
    //设置单据类型下拉
    $.ajax({
        url: strLin + 'billType/selectAll',
        type: 'get',
        dataType: 'json',
        success: function (cdata) {
            $('#billcodetype').combobox({
                valueField: 'sid',
                textField: 'sid',
                data:cdata.data
            });
        }
    });

}

//设置字体大小
function setsizeA() {
    $("#billcodeDate").textbox('textbox').css("font-size", "15px");
    $("#ddh").textbox('textbox').css("font-size", "15px");
    $("#supplier").combobox('textbox').css("font-size", "15px");
    $("#clientName").combobox('textbox').css("font-size", "15px");
    $("#pm").combobox('textbox').css("font-size", "15px");
    $("#cw").textbox('textbox').css("font-size", "15px");
    $("#ps").textbox('textbox').css("font-size", "15px");
    $("#planqty").textbox('textbox').css("font-size", "15px");
    $("#memo").textbox('textbox').css("font-size", "15px");
}

/*****************************************************/

/*设置时间格式*/
function add0(m) {
    return m < 10 ? '0' + m : m
}

function format(shijianchuo) {
    //shijianchuo是整数，否则要parseInt转换
    var time = new Date(shijianchuo);
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    return y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm) + ':' + add0(s);
}
//获取当前时间 不带日期
function getnewdatetime(shijianchuo) {
    //shijianchuo是整数，否则要parseInt转换
    var time = new Date(shijianchuo);
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    return add0(h) + ':' + add0(mm) + ':' + add0(s);
}

/****************************************************/
function checkRate(input) {
    var re = /^[0-9]+.?[0-9]*/;//判断字符串是否为数字//判断正整数/[1−9]+[0−9]∗]∗/
    if (!re.test(input)) {
        // alert('请输入正确的公斤数');
        return false;
    }else
    {
        // alert('正确的数字');
        return true;}
}
function isNotANumber(inputData) {
    //isNaN(inputData)不能判断空串或一个空格
    //如果是一个空串或是一个空格，而isNaN是做为数字0进行处理的，而parseInt与parseFloat是返回一个错误消息，这个isNaN检查不严密而导致的。
    if (parseFloat(inputData).toString() == "NaN") {
        alert('请输入正确的数字');
        return false;
    } else {
        alert('正确的数字');
        return true;
    }
}
/**********************************************************/

//作废保存取消
function tovoidMemoSaveD() {
    let tovoidMemo=$("#tovoidMemoD").textbox('getValue');
    let pass=$("#passD").textbox('getValue');
    if (tovoidMemo==null || tovoidMemo=='' ||tovoidMemo== undefined){
        $.messager.defaults = {ok: "确定", width: 300, closable: false};
        $.messager.alert('提示','作废原因必输，为空不允许保存！')
        return;
    }
    if (pass==null || pass=='' ||pass== undefined){
        $.messager.defaults = {ok: "确定", width: 300, closable: false};
        $.messager.alert('提示','密码必输，为空不允许保存！')
        return;
    }

    $.ajax({
        url: strLin + "dynamicQuery/querySqlString/select * from sys_user where username='"+ username + "' and password='" + pass + "'",
        type: 'get',
        dataType: 'json',
        success: function (cdata) {
            if (cdata.data.length>0){
                console.log('密码正确');

                let etime = new Date();
                let m_date = format(etime);
                let SQLstr={
                    "iid":m_PlanID,
                    "state": 0,
                    "nullify_time": m_date,
                    "nullify_remark":tovoidMemo
                };
                console.log(SQLstr);
                $.ajax({
                    url: strLin + 'material/updateByPrimaryKeySelective',
                    type: 'POST',
                    dataType: 'json',
                    data: JSON.stringify(SQLstr),
                    contentType: "application/json;charset=UTF-8",
                    success: function (data) {
                        console.log(data);
                        $.messager.show({title: "提示", msg: "作废完成！"});
                        addplanA();
                        refresh();

                        $('#D').window('close');
                        $("#tovoidMemoD").textbox("setValue", '');
                        $("#passD").textbox("setValue", '');
                    }
                });

            }else{
                $.messager.defaults = {ok: "确定", width: 300, closable: false};
                $.messager.alert('提示','密码错误！')
                $("#passD").textbox("setValue", '');
                return;
            }

        }
    });


}

function tovoidMemocancelD() {
    $('#D').window('close');
    $("#tovoidMemoD").textbox("setValue", '');
    $("#passD").textbox("setValue", '');
}